#include "LevelExitTrigger.h"
#include "MyGame.h"
#include "Level.h"

LevelExitTrigger::LevelExitTrigger(const Vector2df p, const Vector2df s) : BaseTrigger(p,s)
{
}

LevelExitTrigger::LevelExitTrigger(const Vector2df p, const Vector2df s, CRstring p_levelFileName) : BaseTrigger(p,s)
{
    levelFileName = p_levelFileName;
}

LevelExitTrigger::~LevelExitTrigger()
{

}

//----------------------
// public declarations
//----------------------

void LevelExitTrigger::hit(const SimpleDirection dir, BaseUnit* player, CRstring parameter)
{
    // The player hit the exit, let's mark this level complete
    MyGame *game = MyGame::GetMyGame();
    Level *level = game->GetCurrentLevel();
    game->GetGameState()->SetCurrentState(game->GetCurrentLevelMapName(), level->getLevelName(), "Completed");

    // Now let's load the next level

    if (!level)
    {
        // Somehow we aren't in a level; complain and die
        perror("Critical error: Failed to get current level.");
        exit(-1);
    }
    if (not level->pushed)
    {
        if (levelFileName == "")
        {
            LevelData next = game->GetNextLevel(level->GetFileName());
            if (!(next.FileName == ""))
            {
                level->GoToLevel(next);
            }
            else
            {
                cout << "No next level specified, returning to main menu." << endl;
                level->setNextState(STATE_MAIN);
            }
        }
        else
        {
            level->GoToLevel(levelFileName);
        }
    }
    else
    {
        game->PopState();
    }
}

//----------------------
// private declarations
//----------------------

void LevelExitTrigger::customUpdate()
{
}
